# $@ = целевой файл
# $< = первая зависимость
# $^ = все зависимости

BUILD = build/
SOURCE = src/
KERNEL_BIN = dist/x86_64/kernel.bin
KERNEL_ISO = dist/x86_64/kernel.iso
LINKER = targets/x86_64/linker.ld
SAVE_ISO = targets/x86_64/iso

c_source_files := $(shell find $(SOURCE) -name *.c)
c_object_files := $(patsubst $(SOURCE)%.c, $(BUILD)%.o, $(c_source_files))

asm_source_files := $(shell find $(SOURCE) -name *.asm)
asm_object_files := $(patsubst $(SOURCE)%.asm, $(BUILD)%.o, $(asm_source_files))

x86_64_object_files := $(c_object_files) $(asm_object_files)


$(c_object_files): $(BUILD)%.o : $(SOURCE)%.c
	mkdir -p $(dir $@) && \
	x86_64-elf-gcc -masm=intel -c -I $(SOURCE)include -ffreestanding $(patsubst $(BUILD)%.o, $(SOURCE)%.c, $@) -o $@

$(asm_object_files): $(BUILD)%.o : $(SOURCE)%.asm
	mkdir -p $(dir $@) && \
	nasm -f elf64 $(patsubst $(BUILD)%.o, $(SOURCE)%.asm, $@) -o $@


.PHONY: build-x86_64
build-x86_64: $(x86_64_object_files)
	mkdir -p dist/x86_64 && \
	x86_64-elf-ld -n -o $(KERNEL_BIN) -T $(LINKER) $(x86_64_object_files) && \
	cp $(KERNEL_BIN) $(SAVE_ISO)/boot/kernel.bin && \
	grub-mkrescue /usr/lib/grub/i386-pc -o $(KERNEL_ISO) $(SAVE_ISO)


